function getUrlParams(name) {
    var paramsAry = location.search.substr(1).split('&');
    // 循环数据
    for (var i = 0; i < paramsAry.length; i++) {
        var tmp = paramsAry[i].split('=');
        if (tmp[0] == name) {
            return tmp[1];
        }
    }
    return -1;
}
// 处理日期时间格式
function formDate(date) {
    // 将日期时间字符串转换成日期对象
    date = new Date(date);
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
}

$.ajax({
    type: 'get',
    url: '/posts/random',
    success: function(response) {
        var randomTpl = `
        {{each data}}
        <li>
            <a href="detail.html?id={{$value._id}}">
                <p class="title">{{$value.title}}</p>
                <p class="reading">阅读({{$value.meta.views}})</p>
                <div class="pic">
                    <img src="{{$value.thumbnail}}" alt="" />
                </div>
            </a>
        </li>
        {{/each}}
        `;
        var html = template.render(randomTpl, { data: response });
        $('#randomBox').html(html);
    }
});

$.ajax({
    type: 'get',
    url: '/comments/lasted',
    success: function(response) {
        var tpl = `
        {{each data}}
        <li>
            <a href="javascript:;">
                <div class="avatar">
                    <img src="{{$value.author.avatar}}" alt="" />
                </div>
                <div class="txt">
                    <p><span>{{$value.author.nickName}}</span>{{$value.createAt.split('T')[0]}}说:</p>
                    <p>{{$value.content}}</p>
                </div>
            </a>
        </li>
        {{/each}}
        `;
        var html = template.render(tpl, { data: response });
        $('#commentBox').html(html);
    }
});

$.ajax({
    type: 'get',
    url: '/categories',
    success: function(response) {
        // console.log(response);

        var navTpl = `
        {{each data}}
        <li>
            <a href="list.html?categoryId={{$value._id}}"><i class="fa {{$value.className}}"></i>{{$value.title}}</a>
        </li>
        {{/each}}
        `;
        var html = template.render(navTpl, { data: response });
        $('#topNavBox').html(html);
    }
});

// 获取到搜索表单 并为其添加表单提交事件
$('.search form').on('submit', function() {
    var keys = $(this)
        .find('.keys')
        .val();
    location.href = '/search.html?key=' + keys;
    return false;
});
